const express = require('express');
const router = express.Router();
const { Course, Category, User, Chapter } = require('../../models');
const { Op } = require('sequelize');
const { NotFound, Conflict, BadRequest } = require('http-errors');
const { success, failure } = require('../../utils/responses');
const { coursesIndex } = require('../../utils/meilisearch');
/**
 * 白名单参数过滤
 * */
const filterBody = (data) => {
  return {
    categoryId: data.categoryId,
    // userId: data.userId,
    name: data.name,
    image: data.image,
    recommended: data.recommended,
    introductory: data.introductory,
    content: data.content,
    free: data.free,
  };
};

const conditionParam = {
  attributes: { exclude: ['CategoryId', 'UserId'] },
  include: [
    {
      model: Category,
      as: 'category',
      attributes: ['id', 'name'],
    },
    {
      model: User,
      as: 'user',
      attributes: ['id', 'username', 'avatar'],
    },
  ],
};

/**
 * 公共方法: 查询当前课程
 * */

async function getCourse(req) {
  const { id } = req.params;

  const course = await Course.findByPk(id, conditionParam);
  if (!course) {
    throw new BadRequest(`ID: ${id}的课程为找到`, condition);
  }
  return course;
}

/**
 * 查询课程列表
 * */
router.get('/', async function (req, res) {
  try {
    const query = req.query;
    // 当前第几页，如果不传默认第一页
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    // 当前多少条数据，如果不传默认10条数据
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    // 计算offset
    const offset = (currentPage - 1) * pageSize;

    const condition = {
      ...conditionParam,
      order: [['id', 'DESC']],
      limit: pageSize,
      offset,
    };
    if (query.categoryId) {
      condition.where = {
        categoryId: {
          [Op.eq]: query.categoryId,
        },
      };
    }
    if (query.userId) {
      condition.where = {
        userId: {
          [Op.eq]: query.userId,
        },
      };
    }
    if (query.name) {
      condition.where = {
        name: {
          [Op.like]: `%${query.name}%`,
        },
      };
    }
    if (query.recommended) {
      condition.where = {
        recommended: {
          [Op.eq]: query.recommended === 'true',
        },
      };
    }
    if (query.introductory) {
      condition.where = {
        introductory: {
          [Op.eq]: query.introductory === 'true',
        },
      };
    }
    console.log(condition, 'condition');
    // const courses = await Course.findAll(condition);
    const { count: total, rows } = await Course.findAndCountAll(condition);
    success(res, '查询成功', {
      courses: rows,
      pagination: {
        total,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 查询课程详情
 * */
router.get('/:id', async function (req, res) {
  try {
    const courses = await getCourse(req);
    success(res, '查询成功', { courses });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 创建课程
 * */
router.post('/', async function (req, res) {
  try {
    const body = filterBody(req.body);
    body.userId = req.user.id;
    const courses = await Course.create(body);
    await coursesIndex.addDocuments([
      {
        id: courses.id,
        name: courses.name,
        image: courses.image || null,
        content:courses.content || null,
        likesCount: courses.likesCount || 0,
        updatedAt: courses.updatedAt
      }
    ])
    success(res, '创建成功', { courses }, 201);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 删除课程
 * */
router.delete('/:id', async function (req, res) {
  try {
    const course = await getCourse(req);
    const count = await Chapter.count({ where: { courseId: req.params.id } });
    if (count > 0) {
      throw new Conflict('当前课程存在章节无法删除');
    }
    await course.destroy();
    await coursesIndex.deleteDocuments(course.id)
    success(res, '删除成功');
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 更新课程
 * */
router.put('/:id', async function (req, res) {
  try {
    const course = await getCourse(req);
    const body = filterBody(req.body);
    const data = await course.update(body);
    await coursesIndex.updateDocuments([
      {
        id: data.id,
        name: data.name,
        image: data.image || null,
        content:data.content || null,
        likesCount: data.likesCount || 0,
        updatedAt: data.updatedAt
      }
    ])
    success(res, '更新成功', data);
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
